package ru.myrtle.umf.codegen.java;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class JavaImportBuilder
{
    private static final Set<String> primitiveTypeNames =
            new HashSet<String>(
                    Arrays.asList(
                            "byte"
                    )
            );

    private TreeSet<String> packages;

    public JavaImportBuilder()
    {
        packages = new TreeSet<String>();
    }

    public void addObjectPackage(String objectName)
    {
        if (objectName != null)
        {
            int idx = objectName.lastIndexOf('.');

            if (idx > -1)
            {
                addPackage(objectName.substring(0, idx));
            }
//            else
//            {
//                addPackage(objectName);
//            }
        }
    }

    static boolean isAcceptablePackageName(String namespace, String packageName) {
        if (packageName == null) {
            return false;
        }
        if (packageName.length() <= 0) {
            return false;
        }
        if (packageName.equals(namespace)) {
            return false;
        }
        if (packageName.equals("java.lang")) {
            return false;
        }

        for (String primitiveTypeName : primitiveTypeNames) {
            if (packageName.startsWith(primitiveTypeName)) {
                return false;
            }
        }

        return true;
    }

    public void addPackage(String packageName)
    {
        packages.add(packageName);
    }

    public Collection<String> getImports()
    {
        return Collections.unmodifiableCollection(packages);
    }

    public String getFormattedImports(String namespace)
    {
        StringBuffer buffer = new StringBuffer();

        for (Iterator<String> iter = packages.iterator(); iter.hasNext();)
        {
            String packageName = iter.next();

            if (isAcceptablePackageName(namespace, packageName))
            {
                buffer.append("import").append(' ').append(packageName).append('.').append('*').append(';');
                if (iter.hasNext())
                {
                    buffer.append("\n");
                }
            }
        }

        return buffer.toString();
    }
}
